package com.mengshu.mybatisplus.utils;

import com.mengshu.mybatisplus.basic.BasicPO;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *     Field工具类
 * </p>
 *
 * @author liuning
 * @date 2:06 下午 2022/2/5
 */
public class FieldUtils {

    public static void getFields(Class clazz, List<Field> fields) {
        fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
        if (clazz.getSuperclass() != null) {
            getFields(clazz.getSuperclass(), fields);
        }
    }

    public static Field getField(String fieldName, Class clazz) throws NoSuchFieldException {
        return clazz.getField(fieldName);
    }

    public static Method getFieldMethod(String fieldName, Class clazz) {
        try {
            return new PropertyDescriptor(fieldName, clazz).getReadMethod();
        } catch (IntrospectionException e) {
            return null;
        }
    }

    public static Method getFieldMethod(Field field, Class clazz) {
        try {
            return new PropertyDescriptor(field.getName(), clazz).getReadMethod();
        } catch (IntrospectionException e) {
            return null;
        }
    }

    public static Object getFieldValue(String fieldName, Object object) throws IllegalAccessException, NoSuchFieldException {
        return getFieldValue(getField(fieldName, object.getClass()), object);
    }

    public static Object getFieldValue(Field field, Object object) throws IllegalAccessException {
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        return field.get(object);
    }

    public static void main(String[] args) {
        final List<Field> fields = new ArrayList<>();
        FieldUtils.getFields(BasicPO.class, fields);
        System.out.println(fields.stream().map(p -> p.getName()).collect(Collectors.toList()));
    }
}
